package cc.lucien.web.filter;

import cc.lucien.web.entity.Admin;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class AdminLoginFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String requestURI = request.getRequestURI();
        if (requestURI.equalsIgnoreCase("/ssm/admin/toLogin") ||
        requestURI.equalsIgnoreCase("/ssm/admin/login") ||
        requestURI.contains(".css") || requestURI.contains(".js") ||
        requestURI.contains(".html") || requestURI.contains(".ico") ||
        requestURI.contains(".mp3") || requestURI.contains(".png") ||
        requestURI.contains(".jpg") || requestURI.contains(".jpeg")){
            // 这些放行
            filterChain.doFilter(request,response);
        } else {
            HttpSession session = request.getSession();
            Admin admin = (Admin) session.getAttribute("admin");
            if (admin != null && admin.getName() != null) {
                // 说明登录了
                filterChain.doFilter(request,response);
            }else {
                // 让他去登录
                session.setAttribute("error", "请先登录");
                response.sendRedirect(request.getServletContext().getContextPath()+"/admin/toLogin");
            }
        }
    }

    @Override
    public void destroy() {

    }
}
